package cn.amossun.starter.web.data.security.util;

import javax.servlet.http.HttpServletRequest;

import cn.hutool.core.util.ObjectUtil;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @program: starter-parent
 * @description:
 * @author: Amos.Sun
 * @DateTime: 2020/03/28 17:30
 **/
public class AuthUtil {

    static final String USER_ID = "userId";

    public static String getUserId() {
        if(ObjectUtil.isNull(getRequest())) {
            return null;
        }
        Object object = getRequest().getAttribute(USER_ID);
        if(ObjectUtil.isEmpty(object)) {
            return null;
        }
        return object.toString();
    }

    public static void setUserId(String userId) {
        if(ObjectUtil.isNull(getRequest())) {
            return;
        }
        getRequest().setAttribute(USER_ID, userId);
    }

    public static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        return requestAttributes == null ? null : ((ServletRequestAttributes)requestAttributes).getRequest();
    }

}
